package com.example.pt.controller;

import com.example.pt.entity.TorrentFileES;
import com.example.pt.entity.UserES;
import com.example.pt.enums.Category;
import com.example.pt.service.TorrentFileESSearchService;
import com.example.pt.service.UserESSearchService;
import com.example.pt.utils.DownloadUrlUtils;
import com.example.pt.utils.JWTUtil;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/es")
@CrossOrigin("*")
public class ESController {

    @Autowired
    private TorrentFileESSearchService torrentFileESSearchService;

    @Autowired
    private UserESSearchService userESSearchService;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;

    public record UserSearchResult(Integer uid, String username, String headshot, Integer usertype, Integer points, Integer level) {

    }


    @GetMapping("/search/torrent")
    public ResponseEntity<Map<String, Object>> searchTorrents(@RequestHeader Map<String, String> header,
                                                              @RequestParam String info) {

        String token = header.get("token");
        try{
            JWTUtil.verifyToken(token);
        }catch (Exception e){
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录权限已失效！");
            response.put("status", "fail");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }


        System.out.println(info);
        long startTime = System.currentTimeMillis();
        // 调用服务层单一参数搜索方法
        try {
            List<TorrentFileES> result = torrentFileESSearchService.searchByKeyword(info);

            if(result == null || result.isEmpty()){
                Map<String, Object> response = new HashMap<>();
                response.put("status", "success");
                response.put("message", "查询结果为空！");
                return new ResponseEntity<>(response, HttpStatus.OK);
            }



            long tookMillis = System.currentTimeMillis() - startTime;
            Map<String, List<Map<String, Object>>> categorizedResult = categorizeResult(result);

            Map<String, Object> responseBody = new HashMap<>();
            responseBody.put("categorizedResult", categorizedResult);
            responseBody.put("totalHits", result.size());
            responseBody.put("tookMillis", tookMillis);

            return new ResponseEntity<>(responseBody, HttpStatus.OK);
        }catch (Exception e){
            Map<String, Object> response = new HashMap<>();
            response.put("message", e.getMessage());
            response.put("status", "fail");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

    }

    private Map<String, List<Map<String, Object>>> categorizeResult(List<TorrentFileES> result) {
        return result.stream()
                .collect(Collectors.groupingBy(
                        file -> Category.getNameByValue(file.getCategory()),
                        Collectors.mapping(file -> Map.of(
                                "tid", file.getTid(),
                                "title", file.getTitle(),
                                "category", Category.getNameByValue(file.getCategory()),
                                "description", file.getDescription(),
                                "uploadTime", file.getUploadTime(),
                                "downloadCount", file.getDownloadCount()
                        ), Collectors.toList())
                ));
    }

    @GetMapping("/search/user")
    public ResponseEntity<Map<String, Object>> searchUsers(@RequestHeader Map<String, String> header,
                                                           @RequestParam String info) {
        // JWT认证
        String token = header.get("token");
        try {
            JWTUtil.verifyToken(token);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("status", "fail", "message", "登录权限已失效！"));
        }

        // 执行搜索
        long startTime = System.currentTimeMillis();
        try {
            List<UserES> result = userESSearchService.searchByUsername(info);

            if (result.isEmpty()) {
                return ResponseEntity.ok(Map.of(
                        "status", "success",
                        "message", "查询结果为空！"
                ));
            }

            // 使用记录类替代Map，避免泛型问题
            List<UserSearchResult> userList = result.stream()
                    .map(user -> new UserSearchResult(
                            user.getUid(),
                            user.getUsername(),
                            user.getHeadshot(),
                            user.getUsertype(),
                            user.getPoints(),
                            user.getLevel()
                    ))
                    .collect(Collectors.toList());

            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "userList", userList,  // 直接返回记录类列表
                    "totalHits", userList.size(),
                    "tookMillis", System.currentTimeMillis() - startTime
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("status", "fail", "message", e.getMessage()));
        }
    }

}